package com.ticket.sass.provider.util.util;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * Response处理
 * @author : ywb
 * @date : 2022-01-24 11:14
 */
@Slf4j
public class ResponseUtil {
    /**
     * 输出返回
     */
    public static void out(HttpServletResponse response, String obj) {
        response.setContentType("application/json;charset=UTF-8");
        try (ServletOutputStream out = response.getOutputStream()) {
            out.write(obj.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            log.error(e + "输出JSON出错");
        }
    }
    
    /**
     * 获取目标主机的ip
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = StringUtils.defaultString(request.getHeader("X-Real-IP"),
                    StringUtils.defaultString(request.getHeader("Proxy-Client-IP"),
                    StringUtils.defaultString(request.getHeader("WL-Proxy-Client-IP"),
                    request.getRemoteAddr())));
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
    
    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        return servletRequestAttributes.getRequest();
    }
    
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        return servletRequestAttributes.getResponse();
    }
}